// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
use anyhow::anyhow;
use common::SubFutureInfo;
use std::path::{self, Path};
use tauri::Manager;
pub mod shared;
use shared::{Config, Shared};
use std::sync::Arc;
use tracing::{debug, error, info};

use tauri::Wry;
use tauri::Listener;
use tauri_plugin_store;
use serde_json::json;

type SharedState = Arc<Shared>;

mod command;
pub use command::*;
mod core;
pub use core::{chatdb};

#[derive(Default, Debug, serde::Serialize, serde::Deserialize)]
struct CustomResponse {
    filename: String,
    other_val: usize,
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run(shared: Arc<Shared>) {
    tauri::Builder::default()
        .plugin(tauri_plugin_store::Builder::new().build())
        .plugin(tauri_plugin_clipboard_manager::init())
        .plugin(tauri_plugin_notification::init())
        .plugin(tauri_plugin_dialog::init())
        .setup(|app| {
            #[cfg(dev)] // 仅在调试(dev)版本中包含此代码
            {
                let window = app.get_webview_window("main").unwrap();
                window.open_devtools();
                window.close_devtools();
            }
          
          let builder = tauri_plugin_store::StoreBuilder::new(app, "store.bin");
          if let Err(err) = builder.build() {
              // 如果文件不存在，则创建一个空的文件
              error!("{:?}", err);
          }else{
            info!("store.bin is ok");
          }   

          let webview = app.get_webview_window("main").unwrap();
          webview.listen("hello", |event| {
            if let Ok(payload) = serde_json::from_str::< SubFutureInfo >(&event.payload()) {
                debug!("listen hello, payload = {:?}", payload);
                
                //let wb = app.get_webview_window("main").unwrap();
                //let _r = wb.eval("loaction.reload(true);");
              }
          });
                    
          Ok(())
        })
        .plugin(tauri_plugin_shell::init())
        .manage(shared) // invoke_handler注册的command, sync与async的command 都可以，但需要分别注册！！！
        // .invoke_handler(tauri::generate_handler![get_futures])
        .invoke_handler(tauri::generate_handler![
            chat_chat,
            grep_hello,
            send_channel_abc,
            send_emit_abc,
            get_futures,
            show_notify,
            resource_abc,
            store_abc,
            get_ask_dialog,
            get_msg_dialog,
            get_file_dialog
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

////////
